const { items, connectDB } = require('../public/javascripts/utils');
const item = items(__filename);
// // 连接数据库
// connectDB();
class ItemService {
  async create(itemData) {
    try {
      return await item.create(itemData);
    } catch (error) {
      throw error;
    }
  }

  async update(id, itemData) {
    try {
      const where = { _id: id };
      return await item.update(where, itemData);
    } catch (error) {
      throw error;
    }
  }

  async findById(id) {
    try {
      return await item.findById(id);
    } catch (error) {
      throw error;
    }
  }

  async find(para) {
    console.log("传递过来的参数",para)
    try {
      return await item.findOne(para).select('+password');
    } catch (error) {
      throw error;
    }
  }

  async findAll(ctx) {
    try {
      const pageIndex = parseInt(ctx.pageIndex) || 1
      const pageSize = parseInt(ctx.pageSize) || 10
      const total = await item.countDocuments(ctx)
      const res = await item.find().skip(pageSize * (pageIndex - 1)).limit(pageSize).sort({'date': 1})
      return {res, total}
    } catch (error) {
      throw error;
    }
  }

  async delete(id) {
    try {
      return await item.findByIdAndDelete(id);
    } catch (error) {
      throw error;
    }
  }
}

module.exports = new ItemService();